import { defineStore } from "pinia";
import { IUserInfo, userState, userToken } from '@interface/login'
import { getInfo } from "@api/user";
import router from "@/router";

export const useUserStore = defineStore('storeId', {
  state: () : {
    userInfo: Partial<IUserInfo>;
    userState: userState,
    token: userToken
  } => {
    return {
      userInfo: {},
      userState: false,
      token: ''
    }
  },
  actions: {
    isLogin(token: string) {
      if (token) {
        this.token = token
      }
    },
    setUserInfo(info: IUserInfo) {
      if (this.token) {
        this.userInfo = info
        this.userState = true
      }
    },
    removeUserInfo() {
      this.userInfo = {}
      this.userState = false
      this.token = ''
      router.replace({ path: '/'})
    },
    async getInfo() {
      let res = await getInfo()
      this.setUserInfo(res.data)
    }
  },
  persist: {
    enabled: true,
    stategies: [
      {
        storage: localStorage, //默认是session
        paths: ['userInfo', 'token', 'userState']
      }
    ]
  }
})